<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/7/15
 * Time: 15:44
 */

namespace AppApi\Controller;


use Common\Model\CardModel;
use Common\Model\FutureModel;
use Common\Model\MemberModel;
use Common\Model\MemCardModel;
use Common\Model\OrderModel;
use Common\Model\RecordModel;
use System\Model\DocumentsModel;

class MemberController extends ApiBaseController
{

    private $member_model;
    private $mem_card_model;
    private $record_model;
    private $card_model;
    private $order_model;
    private $future_model;
    private $document_model;

    public function __construct()
    {
        parent::__construct();
        $this->member_model     = new MemberModel();
        $this->mem_card_model   = new MemCardModel();
        $this->record_model     = new RecordModel();
        $this->card_model       = new CardModel();
        $this->order_model      = new OrderModel();
        $this->future_model     = new FutureModel();
        $this->document_model   = new DocumentsModel();
    }

    public function getopenid() {
        $code = I('post.code');
        vendor('WxPayPubHelper.WxPayPubHelper');
        $appid = \WxPayConf_pub::APPID;//'wxb1d5eed80be4e9a2';
        $app_sercet = \WxPayConf_pub::APPSECRET;//'de80375058639d5cbad8d881e86a994d';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$app_sercet."&js_code=".$code."&grant_type=authorization_code";
        $result = file_get_contents($url);
        $data = json_decode($result, true);
        exit($this->returnApiSuccess($data));
    }

    public function getMemberInfo() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $nickname   = I('post.nickname');
        $this->checkparam([$openid]);

        $member_info = $this->member_model->where(['openid' => $openid])->find();
        if(!$member_info) {
            $member_info = $this->member_model->register($openid, $nickname);
            if(!$member_info) {
                exit($this->returnApiError(ApiBaseController::FATAL_ERROR));
            }
        }
        if($member_info['phone']) {
            if($this->mem_card_model->where(['phone' => $member_info['phone']])->find()) {
                $member_info['card'] = 'yes';
            } else {
                $member_info['card'] = 'no';
            }
        } else {
            $member_info['card'] = 'no';
        }

        exit($this->returnApiSuccess($member_info));

    }

    /**
     * 绑定手机号
     */
    public function boundPhone() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $phone      = I('post.phone');
        $this->checkparam([$openid, $phone]);

        if($this->member_model->where(['phone' => $phone])->find()) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '该手机号已绑定用户'));
        }
        if($this->member_model->savePhone($openid, $phone) == false) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '绑定失败，请重试'));
        }
        exit($this->returnApiSuccess());
    }

    public function editInfo() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $child_name      = I('post.child_name');
        $birthday   = I('post.birthday');
        $this->checkparam([$openid, $child_name, $birthday]);


        if($this->member_model->where(['openid' => $openid])->save(['child_name' => $child_name, 'birthday' => $birthday] ) == false) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '失败，请重试'));
        }
        exit($this->returnApiSuccess());
    }

    /**
     * 获取当前会员卡信息
     */
    public function getMyCard() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $this->checkparam([$openid]);

        $phone = $this->member_model->where(['openid' => $openid])->getField('phone');
        if(!$phone) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '请绑定手机号'));
        }

        $card_info = $this->mem_card_model->where(['phone' => $phone])->find();
        if(!$card_info) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '未找到会员卡信息'));
        }
        exit($this->returnApiSuccess($card_info));

    }

    /**
     * 打卡签到
     */
    public function signCard() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $tag        = I('post.tag');
        $this->checkparam([$openid]);

        $member_info = $this->member_model->where(['openid' => $openid])->find();
        if(!$member_info['phone']) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '未绑定手机号'));
        }
        $card_info = $this->mem_card_model->where(['phone' => $member_info['phone']])->find();
        if(!$card_info) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '未找到会员卡信息'));
        }
        $this->mem_card_model->startTrans();
        $is_commit = true;

        if($card_info['type'] == 'times') {
            if($card_info['times'] == 0) {
                exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '次数卡已用完'));
            }
            if($tag == 'swim') {
                if($this->mem_card_model->where(['phone' => $member_info['phone']])->save(['times' => ['exp', 'times-1']]) == false) {
                    $is_commit = false;
                }
            } else {
                if($this->mem_card_model->where(['phone' => $member_info['phone']])->save(['times' => ['exp', 'times-0.5']]) == false) {
                    $is_commit = false;
                }
            }

        }

        if($this->record_model->addOne($card_info['id'], $openid, 'user', $tag, $card_info['phone']) == false) {
            $is_commit = false;
        }
        if($is_commit) {
            $this->mem_card_model->commit();
            exit($this->returnApiSuccess());
        } else {
            $this->mem_card_model->rollback();
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '打卡失败'));
        }
    }

    public function getCardList() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }
        $type = I('post.type');//times period
        $where['type'] = $type;
        $result = $this->card_model->where($where)->select();
        exit($this->returnApiSuccess($result));
    }

    public function createOrder() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $card_id    = I('post.card_id');
        $name       = I('post.name');//姓名
        $this->checkparam([$openid]);

        $member_info = $this->member_model->where(['openid' => $openid])->find();
        if(!$member_info['phone']) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '请先绑定手机号'));
        }
        $card_info  = $this->mem_card_model->where(['phone' => $member_info['phone']])->find();

        if(($card_info['type'] == 'times' && $card_info['times'] > 0 && $card_info['end_time'] > date('Y-m-d H:i:s'))) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '次数卡还有效，不能购买'));
        }
        if($card_info['type'] == 'period' && $card_info['end_time'] > date('Y-m-d H:i:s')) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '时长卡还在有效期内，不能购买'));
        }

        $info = $this->card_model->find($card_id);
        $data = [
            'order_sn'  => $this->order_model->getOrderNumber(),
            'card_id'   => $card_id,
            'openid'    => $openid,
            'mid'       => $member_info['id'],
            'phone'     => $member_info['phone'],
            'price'     => $info['price'],
            'name'      => $name,
            'create_time'   => date('Y-m-d H:i:s'),
            'update_time'   => date('Y-m-d H:i:s'),
        ];

        if($this->order_model->add($data)) {
            exit($this->returnApiSuccess(['order_price' => $info['price'], 'order_sn' => $data['order_sn']]));
        } else {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR));
        }

    }

    public function UnifiedOrder() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $order_sn    = I('post.order_sn');
        $this->checkparam([$openid, $order_sn]);

        vendor('WxPayPubHelper.WxPayPubHelper');
        Vendor('WxPayPubHelper.WeixinPay');

        $order_info = $this->order_model->where(['order_sn' => $order_sn])->find();
        if($order_info['status'] == 'payed') {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '订单已支付，不能重复支付'));
        }
        $appid=\WxPayConf_pub::APPID;
//        $openid= $openid;
        $mch_id=\WxPayConf_pub::MCHID;
        $key=\WxPayConf_pub::KEY;
        $out_trade_no = $order_sn;
        $total_fee = '0.01';//$order_info['order_price'];

        $body = "购卡支付";

        $weixinpay = new \WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee*100, \WxPayConf_pub::NOTIFY_URL);
        $return=$weixinpay->pay();

        exit($this->returnApiSuccess($return));

    }

    public function makeAppointment() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $openid     = I('post.openid');
        $times      = I('post.times');
        $period     = I('post.period');

        $this->checkparam([$openid, $times, $period]);

        if($this->future_model->where(['openid' => $openid, 'times' => $times, 'period' => $period])->find()) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '不能重复预约'));
        }

        if($this->future_model->where(['times' => $times, 'period' => $period])->count() >= 3) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '该时间段超过人数限制'));
        }

        if($this->future_model->add([
            'openid'    => $openid,
            'times'     => $times,
            'period'    => $period,
            'create_time'   => date('Y-m-d H:i:s'),
        ])) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR));
        }
    }

    public function getAbout() {
        $info = $this->document_model->where(['doc_class' => 'about'])->find();

        exit($this->returnApiSuccess(['content' => $info['content']]));

    }
}